package com.mzh.common.security.service;

import cn.hutool.core.lang.UUID;
import cn.hutool.jwt.JWTUtil;
import com.mzh.common.core.constants.CacheConstants;
import com.mzh.common.core.constants.JwtConstants;
import com.mzh.common.redis.service.RedisService;
import com.mzh.common.core.domain.LoginUser;
import com.mzh.common.core.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

//操作用户登录的token方法
@Service
@Slf4j
public class TokenService {

    @Autowired
    private RedisService redisService;

    public String createToken(Long userId, String secret,Integer identity, String nickname, String headImage) {
        Map<String,Object> claims=new HashMap<>();
        String userKey= UUID.fastUUID().toString();
        claims.put(JwtConstants.LOGIN_USER_ID,userId);
        claims.put(JwtConstants.LOGIN_USER_KEY,userKey);
        String token = JwtUtils.createToken(claims, secret);
        //第三方机制中存储的敏感消息 redis

        //身份认证具体还要存储哪些信息   identity //1 表示普通用户，2 表示管理员用户
        //使用什么样的数据类型        String
//            key 必须保持唯一 便于维护 统一前缀：logintoken:userid/userUUID
        String tokenKey= getTokenKey(userKey);
        LoginUser loginUser=new LoginUser();
        loginUser.setIdentity(identity);
        loginUser.setNickName(nickname);
        loginUser.setHeadImage(headImage);
        redisService.setCacheObject(tokenKey,loginUser,CacheConstants.EXP, TimeUnit.MINUTES);

        return token;
    }

    //延长token的有效时间，就是延长redis当中从存储的用于身份认证的敏感消息有效时间
    public void extendToken(Claims claims) {
        String userKey=getUserKey(claims);
        if(userKey==null){
            return;
        }
        String tokenKey=getTokenKey(userKey);

        Long expire = redisService.getExpire(tokenKey, TimeUnit.MINUTES);
        if (expire != null&&expire<CacheConstants.REFRESH_TIME) {
            redisService.expire(tokenKey,CacheConstants.EXP,TimeUnit.MINUTES);
        }
    }


    private String getUserKey(String token,String secret){
        Claims claims = getClaims(token, secret);
        if (claims == null) return null;
        return JwtUtils.getUserKey(claims);
    }



    public Long getUserId(Claims claims){
        if (claims == null) return null;
        return Long.valueOf(JwtUtils.getUserId(claims));
    }

    public String  getUserKey(Claims claims){
        if (claims == null) return null;
        return JwtUtils.getUserKey(claims);
    }

    private String getTokenKey(String userKey){
        return CacheConstants.LOGIN_TOKEN_KEY +userKey;
    }

    public LoginUser  getLoginUser(String token, String secret) {
        String userKey=getUserKey(token,secret);
        if(userKey==null){
            return null;
        }
        return redisService.getCacheObject(getTokenKey(userKey),LoginUser.class);
    }

    public boolean deleteLoginUser(String token, String secret) {
        String userKey=getUserKey(token,secret);
        if(userKey==null){
            return false;
        }
        return redisService.deleteObject(getTokenKey(userKey));
    }

    public Claims getClaims(String token, String secret) {
        Claims claims;

        try {
            claims = JwtUtils.parseToken(token, secret); //获取令牌中信息  解析payload中信息  存储着用户唯一标识信息
            if (claims == null) {
                log.error("解析token：{}，出现异常", token);
                return null;
            }
        } catch (Exception e) {
            log.error("解析token：{}，出现异常", token,e);
            return null;
        }
        return claims;
    }

    //刷新用户信息
    public void refreshLoginUser(String nickName, String headImage,String userKey) {
        String tokenKey = getTokenKey(userKey);
        LoginUser loginUser = redisService.getCacheObject(tokenKey, LoginUser.class);   //从缓存中获取用户信息
        loginUser.setNickName(nickName);
        loginUser.setHeadImage(headImage);
        redisService.setCacheObject(tokenKey, loginUser);
    }
}
